<template>
  <div
    :class="['my-chart', isLandScape ? 'landscape' : '']"
    :id="chartId"
  ></div>
</template>

<script>
import { onMounted, watch } from "vue";
// 按需引入echarts
import * as echarts from "echarts/core";
import {
  GridComponent,
  TooltipComponent,
  DataZoomComponent,
  TitleComponent,
  LegendComponent,
} from "echarts/components";
import { LineChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  GridComponent,
  TooltipComponent,
  DataZoomComponent,
  LegendComponent,
  LineChart,
  TitleComponent,
  CanvasRenderer,
]);

function toHtml(params, valueFommter = (val) => val) {
  let res = `<div style="margin-bottom:5px;font-size:13px;"><strong>时间：${params[0].name}</strong></div>`;
  for (let i = 0; i < params.length; i++) {
    res += `<div class="f-r-b-c" style="-size:12px;"><span>${
      params[i].seriesName
    }：</span><span>${valueFommter(params[i].data)}</span></div>`;
  }
  return res;
}

export default {
  name: "Echart",
  props: {
    chartId: String,
    isLandScape: {
      type: Boolean,
      default: false, // 屏幕方向：竖屏 portrait，横屏 landscape
    },
    data: {
      type: Object,
      default: () => {
        return {
          xAxis: [],
          series: [],
          isLoading: true,
        };
      },
    },
    tooltipValueFormatter: Function,
  },
  setup(props, context) {
    var myChart;
    var option = {
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        // nameLocation: "middle",
        axisTick: {
          alignWithLabel: true, // 刻度和文字居中对齐
        },
        data: [],
        axisLabel: {
          formatter: (val) => val && val.replace(/-/g, "."),
        },
      },
      yAxis: {
        type: "value",
        minInterval: 1,
        axisLabel: {
          formatter: (val) => val,
          margin: 5,
          // rotate: -30,
        },
        // axisLine: {
        //   lineStyle: {
        //     color: "#2494f0",//y轴字体颜色
        //   },
        // },
      },
      grid: {
        left: 35,
        top: 60,
        right: 10,
        borderWidth: 1,
      },
      // dataZoom: [
      //   {
      //     type: "slider",
      //     start: 0,
      //     end: 100,
      //   },
      // ], // 动态渲染slider
      series: [],
      // legend: {
      //   data: ["收入","付费会员","累积会员"],
      // },
    };

    if (props.data.title) {
      if (typeof props.data.title == "string") {
        option.title = [
          {
            top: "10px",
            left: "center",
            text: props.data.title,
          },
        ];
      } else {
        option.title = [props.data.title];
      }
    }

    if (props.tooltipValueFormatter) {
      option.formatter = function (params, ticket, callback) {
        callback(ticket, toHtml(params, props.tooltipValueFormatter));
      };
    }

    if (props.isLandScape) {
      option.grid = {
        //与绝对定位相似，top，left，right，bottom 设定是根据上级盒子宽高来计算
        top: "80px",
        left: "40px",
        right: "40px",
        bottom: "80px",
      };
    }

    function initChart() {
      if (!myChart && props.chartId) {
        myChart = echarts.init(document.getElementById(props.chartId));
        myChart.on("finished", function () {
          console.log("charts [" + props.chartId + "] finished");
        });
      }
    }

    function updateOptionxAxisData(data) {
      option.xAxis.data = [...data];
      if (option.xAxis.data.length >= 10) {
        updateOptionDataZoom(true);
      } else {
        updateOptionDataZoom(false);
      }
    }

    function updateOptionSeriesData(data) {
      option.series = [...data];
    }

    function updateOptionDataZoom(isShowSlider) {
      option.dataZoom = [
        {
          type: "slider",
          start: 0,
          end: 100,
          show: isShowSlider,
        },
      ];
    }

    function renderChart() {
      option && myChart.setOption(option);
    }

    watch(props.data, (val, prevVal) => {
      setTimeout(() => {
        initChart();
        updateOptionxAxisData(val.xAxis);
        updateOptionSeriesData(val.series);
        renderChart();

        if (val.isLoading) {
          myChart.showLoading();
        } else {
          setTimeout(() => {
            myChart.hideLoading();
          }, 1000);
        }
      }, 100);
    });

    return {
      chartId: props.chartId,
    };
  },
};
</script>
<style lang="less" scoped>
.my-chart {
  width: calc(100vw -30px);
  height: 300px;
}
.landscape {
  height: 100vw;
  width: 100vh;
  transform-origin: left top;
  transform: rotate(90deg) translateY(-100vw);
  box-sizing: border-box;
}
</style>